package com.example.smartf.mqtt;

import com.example.smartf.model.MqttCustionMap.SingleMap;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class DownCallback implements MqttCallback {
    //日志记录器
    private Logger logger = LoggerFactory.getLogger(getClass());

    private Lock lock;
    private Condition condition;
    //作为singlemap的唯一标识符，前端传入
    private String username;

    public DownCallback(Lock alock,Condition cond,String usern){
        lock = alock;
        condition = cond;
        username = usern;
    }

    //断开连接
    @Override
    public void connectionLost(Throwable throwable){
        logger.warn("下行--连接异常：mqtt 代理 连接断开！");
    }

    //发送信息成功 回调
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken){
        logger.info("下行--信息发送成功");
    }

    //接受信息成功 回调
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws  Exception{
        lock.lock();
        String message = new String(mqttMessage.getPayload());

        SingleMap singleMap = SingleMap.getInstance();
        singleMap.put(username,message);
        logger.info("下行--收到板子回复：" + singleMap.get(username));
        condition.signalAll();

        lock.unlock();
    }

}
